package cn.dyp.com.agriculture.util;

import android.content.Context;
import android.net.ConnectivityManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 网络连接工具类
 * Created by lenovo on 2017/5/7.
 */

public class NetUtil {
    private static URL mUrl;
    private static HttpURLConnection mConnection;
    private static BufferedReader mReader = null;

    /**
     * 判断网络是否连接
     * @param context 上下文对象
     * @return 网络是否连接
     */
    public static boolean isNetworkAvailable(Context context) {
        boolean isNetworkOK = false;
        try {
            ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);//网络连接服务
            if (null == conn || null == conn.getActiveNetworkInfo()) {
                isNetworkOK = false;
            } else {
                isNetworkOK = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isNetworkOK;
    }

    /**
     * 发送数据
     * @param urlString 网络连接Url
     * @param params 发送的数据（请求body）
     * @return 服务器返回的数据
     */
    public static String sendData(String urlString, String params) {
        String result = "";
        try {
            createConnection(urlString);//创建网络连接
            setParams();//设置网络连接的参数
            writeData(params);//写出数据
            result = readData(result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (mReader != null) {
                try {
                    mReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * 读取数据
     * @param result 数据包
     */
    private static String readData(String result) throws IOException {
        mReader = new BufferedReader(new InputStreamReader(mConnection.getInputStream()));
        String line;
        while ((line = mReader.readLine()) != null) {
            if (result.equals("")) {
                result += line;
            } else {
                result += "\n" + line;
            }
        }
        return result;
    }

    //写出数据
    private static void writeData(String params) throws IOException, UnsupportedEncodingException {
        OutputStream os = mConnection.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");
        osw.write(params);
        osw.flush();
        osw.close();
    }

    //设置网络连接的参数
    private static void setParams() {
        mConnection.setConnectTimeout(20 * 1000);
        mConnection.setReadTimeout(20 * 1000);
        mConnection.setDoOutput(true);
        mConnection.setDoInput(true);
    }

    /**
     * 创建网络连接
     * @param urlString 网络连接的Url
     */
    private static void createConnection(String urlString) throws MalformedURLException, IOException {
        mUrl = new URL(urlString);
        mConnection = (HttpURLConnection) mUrl.openConnection();//openConnection（）返回的URLConnection对象
    }
}
